﻿using CRM.Models;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using CRM.Enums;
using CRM.ViewModels.System;
using Microsoft.AspNetCore.Identity;
using Z.EntityFramework.Plus;

namespace CRM.Controllers.SystemManage
{
    [Route("api/[controller]")]
    [ApiController]
    public class OemController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        public OemController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }

        /// <summary>
        /// OEM列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<ResultStruct> GetList([FromQuery] string name, [FromQuery] States? state)
        {
            var sqlQuery = _dbContext.Oem as IQueryable<Oem>;

            if (state.HasValue)
            {
                sqlQuery = sqlQuery.Where(i => i.State == state);
            }

            if (!string.IsNullOrEmpty(name))
            {
                sqlQuery = sqlQuery.Where(i => i.Name == name);
            }


            var data = await sqlQuery.OrderBy(i => i.State).ThenByDescending(i => i.Id).ToPaginateAsync(Request);
            return Success(data);
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> GetInfo(GetId requestData)
        {
            var row = await _dbContext.Oem.Where(m => m.Id == requestData.Id).FirstOrDefaultAsync();
            return row == null ? Error() : Success(data: row);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> SubAddInfo(OemSubAdd requestData)
        {
            Oem oem = new()
            {
                Name = requestData.Name,
                Title = requestData.Title,
                Style = requestData.Style,
                Domain = requestData.Domain,
                State = requestData.State,
                IconUrl = requestData.IconUrl,
                LogoUrl = requestData.LogoUrl,
                IndexContent = requestData.IndexContent,
                ShowLoginLogo = requestData.ShowLoginLogo,
                ShowIndexLogo = requestData.ShowIndexLogo,
                ShowIndexContent = requestData.ShowIndexContent,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            await _dbContext.Oem.AddAsync(oem);
            await _dbContext.SaveChangesAsync();

            return Success();
        }

        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> SubEditInfo(OemSubEdit requestData)
        {
            var row = await _dbContext.Oem.FindAsync(requestData.Id);
            if (row == null) return Error(message: "无权操作");

            row.Name = requestData.Name;
            row.Title = requestData.Title;
            row.Style = requestData.Style;
            row.Domain = requestData.Domain;
            row.State = requestData.State;
            row.IconUrl = requestData.IconUrl;
            row.LogoUrl = requestData.LogoUrl;
            row.IndexContent = requestData.IndexContent;
            row.ShowLoginLogo = requestData.ShowLoginLogo;
            row.ShowIndexLogo = requestData.ShowIndexLogo;
            row.ShowIndexContent = requestData.ShowIndexContent;

            await _dbContext.SaveChangesAsync();
            return Success();
        }
        
        /// <summary>
        /// 修改邮箱配置
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> EditEmailSettings(OemEmailSettingsEdit requestData)
        {
            var row = await _dbContext.Oem.FindAsync(requestData.OemId);
            if (row == null) return Error(message: "无权操作");

            var settings = row.EmailSettings ?? new OemEmailSettings();
            settings.OemId = requestData.OemId;
            settings.EmailPlatform = requestData.EmailPlatform;
            settings.UseIndependentMailjet = requestData.UseIndependentMailjet;
            settings.MailjetApiKey = requestData.MailjetApiKey;
            settings.MailjetApiSecret = requestData.MailjetApiSecret;
            settings.UseIndependentRushmail = requestData.UseIndependentRushmail;
            settings.RushmailCustomId = requestData.RushmailCustomId;
            settings.RushmailSecretKey = requestData.RushmailSecretKey;

            row.EmailSettings = settings;
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public async Task<ResultStruct> DelInfo(GetId requestData)
        {
            var row = await _dbContext.Oem.FindAsync(requestData.Id);
            if (row == null) return Error(message: "无权操作");

            _dbContext.Oem.Remove(row);
            await _dbContext.SaveChangesAsync();
            //删除 分配信息
            await _dbContext.OemCompany.Where(n => n.OemId == requestData.Id).DeleteAsync();

            return Success();
        }


        [HttpGet("[action]")]
        public async Task<ResultStruct> GetAllotList([FromQuery] AllotData requestData)
        {
            IQueryable<OemCompany> sqlQuery = _dbContext.OemCompany.Where(i => i.OemId == requestData.OemId);
            if (!string.IsNullOrEmpty(requestData.Name))
            {
                sqlQuery = sqlQuery.Where(i => i.AllotUsername == requestData.Name);
            }

            var data = await sqlQuery.OrderByDescending(i => i.Id).ToPaginateAsync(Request);
            return Success(data);
        }

        [HttpPost("[action]")]
        public async Task<ResultStruct> AddAllot(AllotData requestData)
        {
            var waitUser = await _userManager.FindByNameAsync(requestData.Name);
            if (null == waitUser)
            {
                return Error(message: "用户不存在");
            }

            //检测账号名是否存在
            var res = await _dbContext.OemCompany.Where(m => m.OemId == requestData.OemId).Where(m => m.CompanyId == waitUser.CompanyId).FirstOrDefaultAsync();
            if (res != null)
            {
                return Error(null, "用户所属公司已关联");
            }

            var u = _userManager.GetUserAsync(User).Result;

            OemCompany oemCompanyData = new()
            {
                OemId = requestData.OemId,
                CompanyId = waitUser.CompanyId,
                AllotUserId = waitUser.Id,
                AllotUsername = waitUser.UserName,
                OperateTruename = u.TrueName,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            await _dbContext.OemCompany.AddAsync(oemCompanyData);
            await _dbContext.SaveChangesAsync();

            return Success();
        }

        [HttpPost("[action]")]
        public async Task<ResultStruct> DelAllot(GetId requestData)
        {
            var row = await _dbContext.OemCompany.FindAsync(requestData.Id);
            if (row == null) return Error(message: "无权操作");

            _dbContext.OemCompany.Remove(row);
            await _dbContext.SaveChangesAsync();
            return Success();
        }
    }
}